import { Modal, Form, Input, Space, Button, message, Radio, Row, Col, Upload, UploadFile } from 'antd';
const { TextArea } = Input;
import { UploadOutlined } from '@ant-design/icons';
import { useIntl } from "umi";
import React, { useState, useEffect, useRef } from 'react';
import { OPERATE_ADD } from '@/constants';
import { createCompetitionQuestion, updateCompetitionQuestion } from '@/services/competitionQuestion/index';
import { uploadFile } from '@/services/file';
const CompetitionQuestionOperatePanel = ({ operateType, record, closePanel }) => {
    const intl = useIntl();
    const [form] = Form.useForm(operateType === OPERATE_ADD ? { autoFlag: 'ENABLED' } : record);
    const [open, setOpen] = useState(true);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [selectLoading, setSelectLoading] = useState(true);
    //文件上传配置--start
    const [fileList, setFileList] = useState(operateType === OPERATE_ADD ? [] : [{ name: record.fileName, url: '', status: 'done', }]);
    const [file, setFile] = useState({ fileRecordUnCode: '', filePath: '' });
    const onRemove = (file) => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        setFileList(newFileList);
    };
    //自定义的文件上传请求
    const handleUpload = async (options) => {
        const uploadedFile = options.file
        setFileList([uploadedFile]);
        const data = new FormData();
        data.append('file', uploadedFile);
        await uploadFile(data).then(res => {
            if (res.success) {
                setFile({ fileRecordUnCode: res.data.fileRecordUnCode, filePath: res.data.filePath });
                message.success(res.msg)
            } else {
                message.error(res.msg)
            }
        })
    };
    //文件上传配置--end
    const handleOk = async (data) => {
        setConfirmLoading(true);
        if (operateType === OPERATE_ADD) {
            let formData = {
                ...data,
                fileRecordUnCode: file.fileRecordUnCode
            }
            await createCompetitionQuestion(formData).then(res => {
                if (res.success) {
                    message.success(res.msg)
                    setConfirmLoading(false)
                    handleCancel()
                } else {
                    message.error(res.msg)
                    setConfirmLoading(false)
                }
            })
        } else {
            //判断是否上传了新的文件
            let isUpload = file.fileRecordUnCode !== '' ? true : false
            let formData = {
                ...data,
                unCode: record.unCode,
                fileRecordUnCode: record.fileRecordUnCode,
                newFileRecordUnCode: isUpload ? file.fileRecordUnCode : '',
            }
            await updateCompetitionQuestion(formData).then(res => {
                if (res.success) {
                    message.success(res.msg)
                    setConfirmLoading(false)
                    handleCancel()
                } else {
                    message.error(res.msg)
                    setConfirmLoading(false)
                }
            })
        }

    };
    const handleCancel = () => {
        setOpen(false);
    };
    return (
        <>
            <Modal
                title={operateType === OPERATE_ADD ? "新增赛题" : "编辑赛题"}
                open={open}
                destroyOnClose={true}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
                afterClose={closePanel}
                centered={true}
                footer={false}
            >
                <Form
                    name={form}
                    style={{
                        maxWidth: 600,
                    }}
                    onFinish={handleOk}
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 17 }}
                    initialValues={form}
                    autoComplete="on"
                >
                    <Form.Item
                        label="赛题名称"
                        name="name"
                        rules={[
                            {
                                required: true,
                                message: "请输入赛题名称",
                            },
                        ]}
                    >
                        <Input placeholder="请输入赛题名称" />
                    </Form.Item>
                    <Form.Item
                        label="描述"
                        name="description"
                    >
                        <TextArea rows={4} placeholder="请输入赛题描述" maxLength={255} />
                    </Form.Item>
                    <Form.Item
                        label="是否自动生成Flag"
                        name="autoFlag"
                        rules={[
                            {
                                required: true,
                                message: "请输入赛题名称",
                            },
                        ]}
                    >
                        <Radio.Group value={'ENABLED'}>
                            <Radio value={'ENABLED'}>{intl.formatMessage({
                                id: 'component.radio.status.yes',
                                defaultMessage: '是'
                            })}</Radio>
                            <Radio value={'DISABLED'}>{intl.formatMessage({
                                id: 'component.radio.status.no',
                                defaultMessage: '否'
                            })}</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="赛题附件"
                        name="file"
                        rules={[
                            {
                                required: true,
                                message: "请上传赛题附件",
                            },
                        ]}
                    >
                        <Upload
                            fileList={fileList}
                            maxCount={1}
                            customRequest={handleUpload} //自定义上传请求，经过测试发现不能和beforeUpload一起使用
                            onRemove={onRemove}

                        >
                            <Button icon={<UploadOutlined />}>点击上传</Button>
                        </Upload>
                    </Form.Item>
                    <Row justify="end">
                        <Col>
                            <Space>
                                <Button htmlType="button" onClick={handleCancel}>
                                    {intl.formatMessage({
                                        id: 'component.button.cancel',
                                    })}
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    {intl.formatMessage({
                                        id: 'component.button.submit',
                                    })}
                                </Button>
                            </Space>
                        </Col>
                    </Row>

                </Form>
            </Modal>
        </>
    );
};
export default CompetitionQuestionOperatePanel;